package wifiunion.com.notice.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.OnLoadMoreListener;
import com.aspsine.irecyclerview.OnRefreshListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.BaseSubFragment;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.DateTimePickDialogUtil;
import wifiunion.com.notice.DeviceDialogCallBack;
import wifiunion.com.notice.NoticeContact;
import wifiunion.com.notice.R;
import wifiunion.com.notice.adapter.RelevanceNoticeAdapter;
import wifiunion.com.notice.entity.DeviceSelectSth;
import wifiunion.com.notice.entity.NoticeGroup;
import wifiunion.com.notice.entity.NoticeInfoList;
import wifiunion.com.notice.entity.User;
import wifiunion.com.notice.presenter.AddRelevanceNoticePresenter;
import wifiunion.com.notice.presenter.NoticeCopyPresenter;
import wifiunion.com.notice.presenter.NoticeDeleteGroupPresenter;
import wifiunion.com.notice.presenter.NoticeDeletePresenter;
import wifiunion.com.notice.presenter.NoticeGroupListPresenter;
import wifiunion.com.notice.presenter.NoticeListPresenter;
import wifiunion.com.notice.presenter.UpdateNoticeGroupPresenter;
import wifiunion.com.notice.utils.ClickTimeSpanUtil;
import wifiunion.com.notice.utils.SharedPreferencesUtils;
import wifiunion.com.notice.utils.db.DBManager;
import wifiunion.com.notice.widget.DeviceSelectSthDialog;
import wifiunion.com.notice.widget.EditDialog;
import wifiunion.com.notice.widget.LoadMoreFooterView;
import wifiunion.com.notice.widget.TipsDialog;
import wifiunion.com.notice.widget.treedialog.TreefilterCallback;
import wifiunion.com.notice.widget.treedialog.TreefilterDialog;


/**
 * Created by Administrator on 2016/11/28.
 * 关联通知搜索页
 */

public class AddSearchRelevanceFragment extends BaseSubFragment implements NoticeContact.View, NoticeContact.CopyNoticeView, OnLoadMoreListener, OnRefreshListener, View.OnClickListener,NoticeContact.AddRelevanceNoticeView, NoticeContact.UpdategroupView {


    private TextView mExchangeTv, mAddCategoryTv, mDelectCategoryTv, mAddDeviceTv, mHeaderTitle;

    private View devicegroupView;

    private EditText searchEt;

    private TextView delGroupTv;

    private Button searchBtn;

    private LinearLayout filterLayout;

    private TextView mStartDateEt, mEndDateEt;

    private IRecyclerView mRecyclerView;

    private View mMainView;


    private RelevanceNoticeAdapter mAdapter;

    private List<NoticeInfoList> mData = new ArrayList<NoticeInfoList>();


    private int pageNum = 1;

    private int pageSize = 10;

    //1卡片模式
    private int mType = 1;

    private HashMap<String, Object> mParams = new HashMap<>();


    private LoadMoreFooterView mLoadMoreFooterView;


    private LinearLayout mGroupLayout, mListHeaderLayout;
    private TextView mSubGroupTv, mDelGroupTv, mModifyGroupTv;


    private TextView mDeviceGroupContentTv;
    /**
     * state 0 不限制
     * 1  正常
     * 2  过期
     */
    private TextView mNoticeStatusTitleTv, mNoticeStatusContentTv;


    private ArrayList<NoticeGroup> mNoticeGroupList = new ArrayList<>();


    private String mAuthtoken;


    private DeviceSelectSthDialog mselectDialog;

    /**
     * 选中的分组对象
     */
    private NoticeGroup mSelectedGroupEntity;

    private NoticeGroupListPresenter mPresenter;

    private NoticeListPresenter mNoticeListPresenter;

    private NoticeDeletePresenter mNoticeDeletePresenter;

    private NoticeCopyPresenter mNoticeCopyPresenter;


    private NoticeDeleteGroupPresenter mNoticeDeleteGroupPresenter;

    private RelativeLayout emptyRl;
    private RelativeLayout mEmptyGuidell;

    private TextView addGroupTv;

    private TextView sendNoticeTv;

    //当前操作Notice的位置
    private int currentOptIndex;

    private User user;

    private NoticeRecordFragment mNoticeRecordFragment;

    private RelativeLayout noticeDataRl;

    private EditDialog mEditDialog;

    private UpdateNoticeGroupPresenter mUpdateNoticeGroupPresenter;

    private AddRelevanceNoticePresenter mAddRelevanceNoticePresenter;

    /**
     * 是否过期，state  0 不限制   1  正常  2  过期
     */
    private int mNoticeStatus = 0;


    //是否点击查询按钮查询
    private boolean searchByBtn;


    private TextView filterTitleTv;

    private TextView mComfirmTv;

    private NoticeInfoList mNoticeInfoList;
    //当前通知的UUid
    private String noticeUuid;

    private ArrayList<String> uuidList;

    private Handler handler = new Handler();
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mMainView = inflater.inflate(R.layout.fragment_addsearchrelevancefragment, container, false);
        mAuthtoken = SharedPreferencesUtils.getSharedPreferences(Constants.CONFIG_AUTHTOKEN, getActivity());
        mPresenter = new NoticeGroupListPresenter(getActivity(), this);
        mNoticeListPresenter = new NoticeListPresenter(getActivity(), this);
        mNoticeDeletePresenter = new NoticeDeletePresenter(getActivity(), this);
        mNoticeDeleteGroupPresenter = new NoticeDeleteGroupPresenter(getActivity(), this);

        mAddRelevanceNoticePresenter = new AddRelevanceNoticePresenter(getActivity(), this);

        user = SharedPreferencesUtils.getUserSharedPreferences(getContext());
        Bundle bundle = getArguments();
        if (null != bundle) {

                mNoticeInfoList = (NoticeInfoList) bundle.getSerializable("notice");
                noticeUuid = mNoticeInfoList.getUuid();
                uuidList = bundle.getStringArrayList("uuidList");
        }


        initview();

        return mMainView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        searchByBtn = false;
        initData();


    }

    public void onLoadMore() {

        if (mLoadMoreFooterView.canLoadMore() && mAdapter.getItemCount() > 0) {
            mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.LOADING);

            pageNum += 1;
            getNoticeListRequest();
            mRecyclerView.setRefreshing(false);
        }


    }

    @Override
    public void onRefresh() {

//        if (null != mSelectedGroupEntity) {
//            if ("-1".equals(mSelectedGroupEntity.getUuid())) {
//
//                devicegroupView.setVisibility(View.GONE);
//            } else {
//                devicegroupView.setVisibility(View.VISIBLE);
//            }
//        }

        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
        mData.clear();
        mAdapter.notifyDataSetChanged();
        pageNum = 1;
        getNoticeListRequest();
        mRecyclerView.setRefreshing(true);

    }

    @Override
    public void onProgress() {

    }

    @Override
    public void onError(final Object obj) {

        if (null != getActivity()) {
            mRecyclerView.setRefreshing(false);
        }
    }


    @Override
    public void onSuccess(Object obj) {


    }

    @Override
    public void getGroupListSuccess(final Object obj) {

        if (null != getActivity()) {
            mNoticeGroupList.clear();
            NoticeGroup unlimitedcg = new NoticeGroup("", "全部");
            mNoticeGroupList.add(unlimitedcg);
            if (null != obj) {
                ArrayList<NoticeGroup> list = (ArrayList<NoticeGroup>) obj;
                mNoticeGroupList.addAll(list);
            }

            mDeviceGroupContentTv.setText("全部");
        }

    }

    @Override
    public void getNoticeListSuccess(final Object obj) {


        if (null != getActivity()) {

            mRecyclerView.setRefreshing(false);
            mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
//                    ArrayList<NoticeInfoList> list = (ArrayList<NoticeInfoList>) obj;
//                    if(pageNum == 1)
//                    {
//                        mData.clear();
//                    }
//                    mData.addAll(list);

            try {
                JSONObject jsonObject = new JSONObject((String) obj);
                Gson gson = new Gson();
                String data = jsonObject.getString("data");
                ArrayList<NoticeInfoList> list = gson.fromJson(data, new TypeToken<List<NoticeInfoList>>() {
                }.getType());

                if (pageNum == 1) {
                    mData.clear();
                }
                mData.addAll(list);

                if (pageNum == 1)
                {
                    if(null != uuidList && uuidList.size() > 0)
                    {
                        for(int i=0;i<uuidList.size();i++)
                        {

                            for(int j=0;j<mData.size();j++)
                            {
                                if(uuidList.get(i).toString().equals(mData.get(j).getUuid()))
                                {
                                    mData.get(j).setChecked(1);
                                }
                            }

                        }
                    }
                }

               JSONObject pageObj = jsonObject.getJSONObject("pages");
                int totalCount = pageObj.getInt("totalCount");

                mHeaderTitle.setText("通知 (共计" + totalCount + "条)");

            } catch (JSONException e) {
                e.printStackTrace();
            }


            if (null != mData && mData.size() > 0) {
                noticeDataRl.setVisibility(View.VISIBLE);
                emptyRl.setVisibility(View.GONE);
                mEmptyGuidell.setVisibility(View.GONE);
                mRecyclerView.setVisibility(View.VISIBLE);
//                    mData.addAll(list);

                mAdapter.notifyDataSetChanged();


                mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);

            } else {

                if (searchByBtn) {
                    noticeDataRl.setVisibility(View.GONE);
                    emptyRl.setVisibility(View.VISIBLE);
                    mEmptyGuidell.setVisibility(View.GONE);
                    mRecyclerView.setVisibility(View.GONE);
                } else {
                    noticeDataRl.setVisibility(View.GONE);
                    emptyRl.setVisibility(View.GONE);
                    mEmptyGuidell.setVisibility(View.VISIBLE);
                    mRecyclerView.setVisibility(View.GONE);
                }


//                        //显示空页面
//                        noticeDataRl.setVisibility(View.GONE);
//                        emptyRl.setVisibility(View.VISIBLE);
//                        mRecyclerView.setVisibility(View.GONE);
            }
            if ((!noticegroupUuid.contains(";")) && !TextUtils.isEmpty(noticegroupUuid)) {
                for (NoticeGroup cg : mNoticeGroupList) {
                    if (cg.getUuid().equals(noticegroupUuid)) {
                        mSelectedGroupEntity = cg;
                    }
                }
                devicegroupView.setVisibility(View.VISIBLE);
            } else {
                devicegroupView.setVisibility(View.GONE);
            }


        }

    }

    @Override
    public void getNotificationUserSuccess(Object obj) {

    }

    @Override
    public void getNotificationRelGroupList(Object obj) {

    }

    @Override
    public void getNoticeRelGroupMemberListSuccess(Object obj) {

    }

    @Override
    public void addNoticeSBDXSuccess(String noticeUuid) {

    }

    @Override
    public void addSBSDSuccess(Object obj) {

    }


    @Override
    public void onGetDeviceLocListSuccess(Object obj) {

    }

    @Override
    public void onGetDeviceListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeDeviceGroupListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeDeviceGroupUuidSuccess(Object obj) {

    }

    @Override
    public void addNoticeDeviceSuccess(Object obj) {

    }

    @Override
    public void getTopGroupListSuccess(Object obj) {

    }

    @Override
    public void getNoticeTargetListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeTargetRelGroupListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeTargetGroupUuidSuccess(Object obj) {

    }

    @Override
    public void addNoticeTarGetDeviceSuccess(Object obj) {

    }

    @Override
    public void addNoticeDataSuccess(Object obj) {

    }

    @Override
    public void deleteNoticeSuccess(Object obj) {

        //删除本地数据库

        DBManager.getInstance(getContext()).delLocNoticeInfo(mData.get(currentOptIndex).getUuid());
        mData.remove(currentOptIndex);
        mAdapter.notifyDataSetChanged();


    }

    @Override
    public void addNoticeGroupSuccess(Object obj) {
        Toast.makeText(getActivity(), "添加成功~", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void addNoticeRelGroupSuccess(Object obj) {

    }

    @Override
    public void setNoticeFromSuccess(Object obj) {

    }

    @Override
    public void getNoticeDetailSuccess(Object obj) {

    }

    @Override
    public void deleteNoticeGroupSuccess(Object obj) {


        Toast.makeText(getActivity(), "删除成功~", Toast.LENGTH_SHORT).show();
//                mNoticeGroupList.remove(mSelectedGroupEntity);
//                mNoticeGroupList.get(0).setIsSelected(1);
//                mSelectedGroupEntity = mNoticeGroupList.get(0);

        for (NoticeGroup dg : mNoticeGroupList) {
            if (noticegroupUuid.equals(dg.getUuid())) {
                mNoticeGroupList.remove(dg);
                break;
            }
        }
        noticegroupUuid = "";
        mSelectedGroupEntity = null;
        mDeviceGroupContentTv.setText("全部");

        devicegroupView.setVisibility(View.GONE);
        pageNum = 1;
        mData.clear();
        mAdapter.notifyDataSetChanged();
        getNoticeListRequest();


    }


    @Override
    public void setPresenter(BasePresenter tp) {
    }


    @Override
    public void initview() {

        mHeaderTitle = (TextView) mMainView.findViewById(R.id.header_title_tv);
//        Typeface face = Typeface.createFromAsset(getActivity().getAssets(), "fonts/PINGFANG-REGULAR.TTF");
//        mHeaderTitle.setTypeface(Constants.regularface);


        mListHeaderLayout = (LinearLayout) mMainView.findViewById(R.id.list_noticelistheader);

        mHeaderTitle.setText("通知");
        mFilterBtn = (TextView) mMainView.findViewById(R.id.filter_btn);
        if (Constants.ISONLINE_VERSION) {
            mFilterBtn.setVisibility(View.VISIBLE);
            mFilterBtn.setOnClickListener(this);
        }

        mRecyclerView = (IRecyclerView) mMainView.findViewById(R.id.notice_irecyclerView);


        devicegroupView = (View) mMainView.findViewById(R.id.device_group_rl);
        addGroupTv = (TextView) mMainView.findViewById(R.id.group_add_tv);
        addGroupTv.setVisibility(View.GONE);

        mDeviceGroupContentTv = (TextView) mMainView.findViewById(R.id.sub_header_filter_content1_tv);
        mDeviceGroupContentTv.setOnClickListener(this);

        filterTitleTv = (TextView) mMainView.findViewById(R.id.sub_header_filter_title1_tv);
        filterTitleTv.setText("通知分组");


        filterLayout = (LinearLayout) mMainView.findViewById(R.id.sub_header_filter_layout2);
        filterLayout.setVisibility(View.GONE);
        mNoticeStatusTitleTv = (TextView) mMainView.findViewById(R.id.sub_header_filter_title2_tv);
        mNoticeStatusTitleTv.setText("状态");


        mNoticeStatusContentTv = (TextView) mMainView.findViewById(R.id.sub_header_filter_content2_tv);
        mNoticeStatusContentTv.setOnClickListener(this);
        initSelectNoticeStatus(mNoticeStatus);
        searchEt = (EditText) mMainView.findViewById(R.id.search_edt);
        searchEt.setHint("输入通知内容");

        noticeDataRl = (RelativeLayout) mMainView.findViewById(R.id.notice_data_rl);
        emptyRl = (RelativeLayout) mMainView.findViewById(R.id.empty_rl);
        mEmptyGuidell = (RelativeLayout) mMainView.findViewById(R.id.empty_guide_rl);


        sendNoticeTv = (TextView) mMainView.findViewById(R.id.sendnotice_tv);
        sendNoticeTv.setOnClickListener(this);

        mLoadMoreFooterView = (LoadMoreFooterView) mRecyclerView.getLoadMoreFooterView();

        mRecyclerView.setOnLoadMoreListener(this);
        mRecyclerView.setOnRefreshListener(this);

        mExchangeTv = (TextView) mMainView.findViewById(R.id.header_exchange_tv);
        mExchangeTv.setVisibility(View.GONE);
        mAddDeviceTv = (TextView) mMainView.findViewById(R.id.header_add_tv);
        mAddDeviceTv.setVisibility(View.GONE);

        mStartDateEt = (TextView) mMainView.findViewById(R.id.startdate_tv);

        mStartDateEt.setOnClickListener(this);


        mEndDateEt = (TextView) mMainView.findViewById(R.id.enddate_tv);
        mEndDateEt.setOnClickListener(this);

        delGroupTv = (TextView) mMainView.findViewById(R.id.group_del_tv);
        delGroupTv.setOnClickListener(this);

        mModifyGroupTv = (TextView) mMainView.findViewById(R.id.group_modeify_tv);
        mModifyGroupTv.setOnClickListener(this);

        searchBtn = (Button) mMainView.findViewById(R.id.search_btn);
        searchBtn.setOnClickListener(this);

        mMainView.findViewById(R.id.back).setOnClickListener(this);

        mComfirmTv = (TextView) mMainView.findViewById(R.id.self_comfirm_tv);
        mComfirmTv.setOnClickListener(this);

        refreshView(mType);
    }


    @Override
    public void initData() {

//        mNoticeGroupList.clear();
//        //默认添加一个分组
//        NoticeGroup unlimitedcg = new NoticeGroup("-1", "全部");
//        mNoticeGroupList.add(unlimitedcg);
//        mNoticeGroupList.get(0).setIsSelected(1);
//        mSelectedGroupEntity = mNoticeGroupList.get(0);
        getGroupListRequest();

        pageNum = 1;
        mData.clear();
//        getNoticeListRequest();
        //设置下拉刷新可用
        mRecyclerView.setRefreshing(true);

    }

    public void getGroupListRequest() {
        String authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);

        try {
            mCommunityUuid = TextUtils.isEmpty(mCommunityUuid) ? user.getCommunityUuid() : mCommunityUuid;
        } catch (Exception e) {
            e.printStackTrace();
            mCommunityUuid = "";
        }
        params.put("communityUuid", mCommunityUuid);

        mPresenter.getGoupList(params);
    }

    public void getNoticeListRequest() {

        String authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);
        params.put("pageNum", String.valueOf(pageNum));
        params.put("pageSize", String.valueOf(pageSize));

//        if (!"-1".equals(mSelectedGroupEntity.getUuid())) {
//            params.put("groupUuid", mSelectedGroupEntity.getUuid());
//        }
        params.put("groupUuid", noticegroupUuid);

        if (!TextUtils.isEmpty(mStartDateEt.getText())) {
            params.put("startDate", mStartDateEt.getText().toString());
        }
        if (!TextUtils.isEmpty(mEndDateEt.getText())) {
            params.put("endDate", mEndDateEt.getText().toString());
        }
        if (null != searchEt.getText().toString() && searchEt.getText().toString().length() > 0) {
            params.put("content", searchEt.getText().toString());
        }


        try {
            mCommunityUuid = TextUtils.isEmpty(mCommunityUuid) ? user.getCommunityUuid() : mCommunityUuid;
        } catch (Exception e) {
            e.printStackTrace();
            mCommunityUuid = "";
        }
        params.put("communityUuid", mCommunityUuid);

        params.put("state", mNoticeStatus);
        mNoticeListPresenter.getNoticeList(params);
    }


    @Override
    public void onClick(View v) {

        if (ClickTimeSpanUtil.isFastDoubleClick()) {
            return;
        }
        int i1 = v.getId();
        if (i1 == R.id.header_exchange_tv) {
            if (mType == 0) {
                mType = 1;
                refreshView(mType);
            } else {
                mType = 0;
                refreshView(mType);
            }

        } else if (i1 == R.id.sub_header_filter_content2_tv) {
            ArrayList<DeviceSelectSth> locdata = new ArrayList<DeviceSelectSth>();
            for (int i = 0; i < 3; i++) {
                DeviceSelectSth dd = new DeviceSelectSth();
                dd.setSelected(false);
                if (mNoticeStatus == i) {
                    dd.setSelected(true);
                } else {
                    dd.setSelected(false);
                }
                switch (i) {
                    case 0:
                        dd.setName("全部");
                        break;
                    case 1:
                        dd.setName("正常");
                        break;
                    case 2:
                        dd.setName("过期");
                        break;
                }

                locdata.add(dd);
            }

            mselectDialog = new DeviceSelectSthDialog(getContext(), locdata, mNoticeStatusCallback);
            mselectDialog.setTitleMsg("选择通知状态");
            mselectDialog.show();

        } else if (i1 == R.id.sub_header_filter_content1_tv) {
            ArrayList<DeviceSelectSth> groupdata = new ArrayList<DeviceSelectSth>();
            for (NoticeGroup deviceGroup : mNoticeGroupList) {
                DeviceSelectSth dd = new DeviceSelectSth();
                dd.setSelected(deviceGroup.getIsSelected() == 1 ? true : false);
                dd.setName(deviceGroup.getName());
                groupdata.add(dd);
            }
            mselectDialog = new DeviceSelectSthDialog(getContext(), groupdata, mDeviceGroupCallback);
            mselectDialog.setTitleMsg("选择分组");
            mselectDialog.show();

        } else if (i1 == R.id.startdate_tv) {
            DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                    getActivity(), mStartDateEt.getText().toString());
            dateTimePicKDialog.dateTimePicKDialog(mStartDateEt);

        } else if (i1 == R.id.enddate_tv) {
            DateTimePickDialogUtil dateTimePicKDialog2 = new DateTimePickDialogUtil(
                    getActivity(), mEndDateEt.getText().toString());
            dateTimePicKDialog2.dateTimePicKDialog(mEndDateEt);

        } else if (i1 == R.id.group_add_tv) {
        } else if (i1 == R.id.group_del_tv) {
            if (mSelectedGroupEntity != null) {
                try {
                    if (!mSelectedGroupEntity.getCommunityUuid().equals(user.getCommunityUuid())) {
                        Toast.makeText(getContext(), getResources().getString(R.string.datasync_noselfdata_tips), Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                final TipsDialog deleteDialog = new TipsDialog(getContext());
                deleteDialog.setTitleMsg("删除分组确认");
                deleteDialog.setMsgHint("删除分组后不可恢复，确定要删除分组吗？");
                deleteDialog.setCancelListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteDialog.dismiss();
                    }
                });
                deleteDialog.setComfirmListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        deleteNoticeGroup();
                        deleteDialog.dismiss();


                    }
                });

                deleteDialog.show();
            }

        } else if (i1 == R.id.header_add_tv || i1 == R.id.sendnotice_tv) {
//            if (HumenCommonUtils.exitAuthority(user, Constants.MENU_NOTICEMANGER_ADD)) {

//                AddRecognitionTargetFragment atf = new AddRecognitionTargetFragment();
//                Bundle bundle = new Bundle();
//                bundle.putInt("pageType", 0);
//                atf.setArguments(bundle);
//                getFragmentManager().beginTransaction().replace(R.id.reight_fl, atf, "42").addToBackStack(null).commit();




                AddRelevanceNoticeFragment atf = new AddRelevanceNoticeFragment();
                Bundle bundle = new Bundle();
                bundle.putInt("pageType", 0);
                atf.setArguments(bundle);
                getFragmentManager().beginTransaction().replace(R.id.reight_fl, atf, "55").addToBackStack(null).commit();
//            } else {
//                Toast.makeText(getContext(), "权限不足，无法操作", Toast.LENGTH_SHORT).show();
//            }


        } else if (i1 == R.id.search_btn) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);

//                if (null != mSelectedGroupEntity) {
//                    if ("".equals(mSelectedGroupEntity.getUuid())) {
//
//                        devicegroupView.setVisibility(View.GONE);
//                    } else {
//                        devicegroupView.setVisibility(View.VISIBLE);
//                    }
//                }

            pageNum = 1;
            mData.clear();
            mAdapter.notifyDataSetChanged();

            searchByBtn = true;
            getNoticeListRequest();
//                mRecyclerView.setRefreshing(true);


        } else if (i1 == R.id.self_comfirm_tv) {
            //获取选中的关联通知
            getChooseRelevanceList();
        } else if (i1 == R.id.back) {
            getFragmentManager().popBackStack();

        }
    }

    public void getChooseRelevanceList(){
        ArrayList<NoticeInfoList> tempNoticeInfoList = new ArrayList<NoticeInfoList>();
        for( NoticeInfoList list : mData)
        {
            if(list.getChecked() == 1){
                tempNoticeInfoList.add(list);
            }
        }
        if(tempNoticeInfoList.size() >0)
        {
            StringBuffer sb = new StringBuffer();
            for(int i=0;i<tempNoticeInfoList.size();i++)
            {
                sb.append(tempNoticeInfoList.get(i).getUuid());
                if (i < tempNoticeInfoList.size() - 1) {
                    sb.append(",");
                }
            }

            addRelevance(sb.toString());

        }else
        {
            addRelevance("");


        }
    }

    //添加关联操作
    private void addRelevance(String targetUuid)
    {
        String authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);
        params.put("uuid", noticeUuid);
        params.put("targetUuid", targetUuid);
        mAddRelevanceNoticePresenter.addRelevanceNotice(params);
    }


    public void deleteNoticeGroup() {

        String authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);
        params.put("uuid", mSelectedGroupEntity.getUuid());
        mNoticeDeleteGroupPresenter.deleteNoticeGroup(params);
    }


    private void refreshView(int type) {

        mAdapter = new RelevanceNoticeAdapter(getActivity(), type, mData, itemclick);
        if (type == 1) {
//            mListHeaderLayout.setVisibility(View.GONE);
//            mExchangeTv.setText("切换到列表视图");
//            Drawable leftDrawable = getResources().getDrawable(R.drawable.exchange_icon);
//            leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());
//            mExchangeTv.setCompoundDrawablePadding(getResources().getDimensionPixelSize(R.dimen.dp_5));
//            mExchangeTv.setCompoundDrawables(leftDrawable, null, null, null);

            mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
            noticeDataRl.setBackgroundResource(R.color.gray10);
        } else {
            mListHeaderLayout.setVisibility(View.VISIBLE);
            mExchangeTv.setText("切换到卡片视图");
            Drawable leftDrawable = getResources().getDrawable(R.drawable.grid_exchange_icon);
            leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());
            mExchangeTv.setCompoundDrawablePadding(getResources().getDimensionPixelSize(R.dimen.dp_5));
            mExchangeTv.setCompoundDrawables(leftDrawable, null, null, null);

            mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            noticeDataRl.setBackgroundResource(R.color.white);
        }
        mRecyclerView.setIAdapter(mAdapter);
    }

    public void delNotice(NoticeInfoList notice) {
        String authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);
        params.put("uuid", notice.getUuid());
        mNoticeDeletePresenter.deleteNotice(params);
    }

    /**
     * 复制通知的请求
     *
     * @param notice
     */
    public void copyNotice(NoticeInfoList notice) {
        String authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);
        params.put("uuid", notice.getUuid());
        mNoticeCopyPresenter = new NoticeCopyPresenter(getContext(), this);
        mNoticeCopyPresenter.copyNotice(params);
    }

    private View.OnClickListener itemclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

//            if (ClickTimeSpanUtil.isFastDoubleClick()) {
//                return;
//            }
//            int i = v.getId();
//            if (i == R.id.notice_grid_item_delete_tv || i == R.id.notice_list_item_delete_tv) {
//                currentOptIndex = Integer.parseInt(String.valueOf(v.getTag()));
//
//
//                try {
//                    if (!mData.get(currentOptIndex).getCommunityUuid().equals(user.getCommunityUuid())) {
//                        Toast.makeText(getContext(), getResources().getString(R.string.datasync_noselfdata_tips), Toast.LENGTH_SHORT).show();
//                        return;
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//                if (HumenCommonUtils.exitAuthority(user, Constants.MENU_NOTICEMANGER_DEL)) {
//                    //删除通知
////                        currentOptIndex = Integer.parseInt(String.valueOf(v.getTag()));
//                    final TipsDialog deleteDialog = new TipsDialog(getContext());
//                    deleteDialog.setTitleMsg("删除通知确认");
//                    deleteDialog.setMsgHint("删除通知后不可恢复，确定要删除通知吗？");
//                    deleteDialog.setCancelListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            deleteDialog.dismiss();
//                        }
//                    });
//                    deleteDialog.setComfirmListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//
//
//                            NoticeInfoList notice = mData.get(currentOptIndex);
//                            delNotice(notice);
//                            deleteDialog.dismiss();
//
//
//                        }
//                    });
//
//                    deleteDialog.show();
//                } else {
//                    Toast.makeText(getContext(), getResources().getString(R.string.no_auth), Toast.LENGTH_SHORT).show();
//                }
//
//
//            } else if (i == R.id.notice_grid_item_look_tv || i == R.id.notice_list_item_look_tv) {
//                if (HumenCommonUtils.exitAuthority(user, Constants.MENU_NOTICEMANGER_LOOKUP)) {
//
//                    //查看通知
//                    currentOptIndex = Integer.parseInt(String.valueOf(v.getTag()));
//                    NoticeInfoList notice = mData.get(currentOptIndex);
//                    AddRecognitionTargetFragment atf = new AddRecognitionTargetFragment();
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("notice", notice);
//                    bundle.putInt("pageType", 1);
//                    atf.setArguments(bundle);
//                    getFragmentManager().beginTransaction().replace(R.id.reight_fl, atf, "42").addToBackStack(null).commit();
//                } else {
//                    Toast.makeText(getContext(), getResources().getString(R.string.no_auth), Toast.LENGTH_SHORT).show();
//                }
//
//
//            } else if (i == R.id.notice_grid_item_edit_tv || i == R.id.notice_list_item_edit_tv) {
//                currentOptIndex = Integer.parseInt(String.valueOf(v.getTag()));
//
//
//                try {
//                    if (!mData.get(currentOptIndex).getCommunityUuid().equals(user.getCommunityUuid())) {
//                        Toast.makeText(getContext(), getResources().getString(R.string.datasync_noselfdata_tips), Toast.LENGTH_SHORT).show();
//                        return;
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//                if (HumenCommonUtils.exitAuthority(user, Constants.MENU_NOTICEMANGER_EDIT)) {
//                    currentOptIndex = Integer.parseInt(String.valueOf(v.getTag()));
//                    NoticeInfoList editnotice = mData.get(currentOptIndex);
//                    AddRecognitionTargetFragment editatf = new AddRecognitionTargetFragment();
//                    Bundle editbundle = new Bundle();
//                    editbundle.putSerializable("notice", editnotice);
//                    editbundle.putInt("pageType", 2);
//                    editatf.setArguments(editbundle);
//                    getFragmentManager().beginTransaction().replace(R.id.reight_fl, editatf, "42").addToBackStack(null).commit();
//
//                } else {
//                    Toast.makeText(getContext(), getResources().getString(R.string.no_auth), Toast.LENGTH_SHORT).show();
//                }
//
//
//            } else if (i == R.id.notice_grid_item_record_tv || i == R.id.notice_list_record_tv) {
//                if (HumenCommonUtils.exitAuthority(user, Constants.MENU_NOTICEMANGER_RECORD)) {
//
//
//                    currentOptIndex = Integer.parseInt(String.valueOf(v.getTag()));
//                    mNoticeRecordFragment = new NoticeRecordFragment();
//                    NoticeInfoList notice = mData.get(currentOptIndex);
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("notice", notice);
//                    mNoticeRecordFragment.setArguments(bundle);
//
//                    getFragmentManager().beginTransaction().add(R.id.reight_fl, mNoticeRecordFragment, "41").hide(AddSearchRelevanceFragment.this).commitAllowingStateLoss();
//
//
//                } else {
//                    Toast.makeText(getContext(), getResources().getString(R.string.no_auth), Toast.LENGTH_SHORT).show();
//                }
//
//
//            } else if (i == R.id.notice_list_item_copy_tv || i == R.id.notice_grid_item_copy_tv) {
//                currentOptIndex = Integer.parseInt(String.valueOf(v.getTag()));
//
//
//                try {
//                    if (!mData.get(currentOptIndex).getCommunityUuid().equals(user.getCommunityUuid())) {
//                        Toast.makeText(getContext(), getResources().getString(R.string.datasync_noselfdata_tips), Toast.LENGTH_SHORT).show();
//                        return;
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//
//                if (HumenCommonUtils.exitAuthority(user, Constants.MENU_NOTICEMANGER_EDIT)) {
//                    //删除通知
//                    currentOptIndex = Integer.parseInt(String.valueOf(v.getTag()));
//                    final TipsDialog copyDialog = new TipsDialog(getContext());
//                    copyDialog.setTitleMsg("通知复制确认");
//                    copyDialog.setMsgHint("确定要复制这条通知吗？");
//                    copyDialog.setCancelListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            copyDialog.dismiss();
//                        }
//                    });
//                    copyDialog.setComfirmListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//
//
//                            NoticeInfoList notice = mData.get(currentOptIndex);
//                            copyNotice(notice);
//                            copyDialog.dismiss();
//
//
//                        }
//                    });
//
//                    copyDialog.show();
//                } else {
//                    Toast.makeText(getContext(), getResources().getString(R.string.no_auth), Toast.LENGTH_SHORT).show();
//                }
//
//            } else if (i == R.id.member_grid_item_path_rl) {
//                try {
//                    currentOptIndex = Integer.parseInt(String.valueOf(v.getTag()));
//                    NoticeInfoList notice = mData.get(currentOptIndex);
//                    showTreePath(notice.getCommunityUuid());
//                } catch (NumberFormatException e) {
//                    e.printStackTrace();
//                }
//
//            }
//
//
        }
    };
    private String noticegroupUuid = "";

    private DeviceDialogCallBack mDeviceGroupCallback = new DeviceDialogCallBack() {
        @Override
        public void updateList(ArrayList<DeviceSelectSth> data) {

            String consumergrouptv = "";
            noticegroupUuid = "";
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).isSelected()) {

                    noticegroupUuid += (mNoticeGroupList.get(i).getUuid() + ";");
                    try {
                        if (TextUtils.isEmpty(mNoticeGroupList.get(i).getName()) || "null".equals(mNoticeGroupList.get(i).getName())) {
                            consumergrouptv += ("全部" + ";");
                        } else {
                            consumergrouptv += (mNoticeGroupList.get(i).getName() + ";");
                        }
                    } catch (Exception e) {
                        consumergrouptv += ("全部" + ";");
                    }
                }
            }

            try {
                noticegroupUuid = (TextUtils.isEmpty(noticegroupUuid)) ? "" : noticegroupUuid;
                consumergrouptv = (TextUtils.isEmpty(consumergrouptv)) ? "全部" : consumergrouptv;

                if (noticegroupUuid.lastIndexOf(";") == (noticegroupUuid.length() - 1)) {
                    noticegroupUuid = noticegroupUuid.substring(0, (noticegroupUuid.length() - 1));
                }
                if (consumergrouptv.lastIndexOf(";") == (consumergrouptv.length()) - 1) {
                    consumergrouptv = consumergrouptv.substring(0, (consumergrouptv.length() - 1));
                }
                mDeviceGroupContentTv.setText(consumergrouptv);
            } catch (Exception e) {
                noticegroupUuid = "";
                mDeviceGroupContentTv.setText("全部");
            }

            pageNum = 1;
            mData.clear();
            mAdapter.notifyDataSetChanged();

            searchByBtn = true;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    searchEt.setText("");
                }
            });
            getNoticeListRequest();

        }
    };


    private DeviceDialogCallBack mNoticeStatusCallback = new DeviceDialogCallBack() {
        @Override
        public void updateList(ArrayList<DeviceSelectSth> data) {

            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).isSelected()) {
                    mNoticeStatus = i;
                }
            }
            initSelectNoticeStatus(mNoticeStatus);
        }
    };

    private void updateNoticeGroupRequest(String uuid, String name) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("Authorization", mAuthtoken);
        params.put("uuid", uuid);
        params.put("name", name);
        mUpdateNoticeGroupPresenter.start(params);
    }


    @Override
    public void onUpdateNoticeGroupSuccess() {
        if (mEditDialog != null && mEditDialog.isShowing()) {

            mData.clear();
            getNoticeListRequest();
            mSelectedGroupEntity.setName(mEditDialog.getEditData());
            mDeviceGroupContentTv.setText(mSelectedGroupEntity.getName());
            mEditDialog.dismiss();
            Toast.makeText(getActivity(), "分组名修改成功~", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onUpdateNoticeGroupFailed() {
        if (mEditDialog != null && mEditDialog.isShowing()) {


            if (mEditDialog != null && mEditDialog.isShowing()) {
                mEditDialog.dismiss();
                Toast.makeText(getActivity(), "更新分组失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onCopyNoticeSuccess() {
        onRefresh();
        Toast.makeText(getActivity(), "复制成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCopyNoticeFailed(final Object object) {
        if (object != null) {
            Toast.makeText(getActivity(), (String) object, Toast.LENGTH_SHORT).show();

        }
    }

    private void initSelectNoticeStatus(int status) {
        switch (status) {
            case 0:
                mNoticeStatusContentTv.setText("全部");
                break;
            case 1:
                mNoticeStatusContentTv.setText("正常");
                break;
            case 2:
                mNoticeStatusContentTv.setText("过期");
                break;
        }
    }

    private TextView mFilterBtn;

    private String mCommunityUuid;
    /**
     * 筛选框 回调的
     */
    public TreefilterCallback mTreefilterCallback = new TreefilterCallback() {
        @Override
        public void onComfirmClicked(ArrayList<String> result) {

            mCommunityUuid = "";
            for (String str : result) {
//                Log.e(Constants.TAG, "str===>" + str);
                mCommunityUuid += (str + ";");
            }
            mCommunityUuid = mCommunityUuid.isEmpty() ? "-1" : mCommunityUuid;
//            getGroupListRequest();
//            getNoticeListRequest();
            initData();
        }
    };

    /**
     * 点击筛选 弹框
     */
    private void filterData() {
        TreefilterDialog tfd = new TreefilterDialog(getContext(), getActivity(), Constants.MENU_NOTICEMANGER, mTreefilterCallback, mCommunityUuid, 0);
        tfd.setTitleMsg("筛选");
        tfd.show();
    }


    /**
     * @param communityUuid
     */
    private void showTreePath(String communityUuid) {
        TreefilterDialog tfd = new TreefilterDialog(getContext(), getActivity(), Constants.MENU_DEVICEMANGER, mTreefilterCallback, communityUuid, 1);
        tfd.setTitleMsg("数据来源");
        tfd.show();
    }

    @Override
    public void addRelevanceNoticeSuccess(Object data) {
        sendResult(Activity.RESULT_OK);
        getFragmentManager().popBackStack();

    }
    private void sendResult(int resultOk) {
        if(getTargetFragment() == null){
            return;
        }else{
            Intent i = new Intent();
            getTargetFragment().onActivityResult(getTargetRequestCode(),resultOk,i);
        }
    }



    @Override
    public void addRelevanceNoticeFailed(Object object) {

    }
}
